<template>
    <div class="w100 h100 table-grid">
        <div class="headButton"
            v-if="tableGridConfigObj.isDeletable || tableGridConfigObj.isAddable || (tableGridConfigObj.isQueriable && queryFieldsConfig.length)">
            <div class="queryContainer">
                <div class="queryContent" v-if="tableGridConfigObj.isQueriable && queryFieldsConfig.length">
                    <queryForm v-model:search-form-data="searchFormData" :form-item-configs="queryFieldsConfig"
                        @search="searchData" />
                </div>
            </div>
        </div>

        <div class="tableContainer">
            <el-card>
                <template #header>
                    <div class="page_card_header">
                        <span class="page_card_header_title">表格名称</span>
                        <div class="page_card_header_btn">
                            <el-button type="primary" @click="showAddForm" v-if="tableGridConfigObj.isAddable">
                                <el-icon>
                                    <Plus />
                                </el-icon>
                                新增
                            </el-button>
                            <el-button type="danger" :disabled="isDisableDelete" @click="deleteRow">
                                <el-icon>
                                    <Delete />
                                </el-icon>
                                删除
                            </el-button>
                        </div>
                    </div>
                    <div class="page_card_header_toolbar">
                        <span>已选择 {{ allCheck ? tableGridObj.paginationConfig.total : selectedRows.length }}
                            项</span>
                        <div class="page_card_header_toolbar_right">
                            <span @click="checkAllChange(false)" v-show="allCheck == true">取消选择</span>
                            <span class="all_chect_btn" @click="checkAllChange(true)"
                                :style="{ color: allCheck ? '#409EFF' : '#868991' }">全部选择</span>
                        </div>
                    </div>
                </template>
                <el-table ref="tableRef" :data="tableGridObj.tableData" @selection-change="tableSelectChange"
                    style="width: 100%;" max-height="400" :cell-style="{ textAlign: 'center' }"
                    @select="handleSelectChange" :header-cell-style="{ textAlign: 'center' }">
                    <el-table-column type="selection" width="55" fixed="left" />
                    <el-table-column v-for="(item, index) in tableFieldsConfig" :key="index" :label="item.fieldName"
                        :width="item.fieldWidth">
                        <template #default="scope">
                            <el-switch v-if="item.fieldType === 'ElSwitch'" disabled
                                v-model="scope.row[item.fieldCode]" />
                            <el-color-picker v-else-if="item.fieldType === 'ElColorPicker'" disabled
                                v-model="scope.row[item.fieldCode]" />
                            <span v-else-if="item.isTranslate">{{ item.translateFieldCode &&
                                scope.row[item.translateFieldCode] }}</span>
                            <span v-else>{{ scope.row[item.fieldCode] }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="200" fixed="right">
                        <template #default="scope">
                            <el-button type="info" @click="showDetails(scope.row)"><el-icon>
                                    <View />
                                </el-icon>查看</el-button>
                            <el-button type="success" v-if="tableGridConfigObj.isEditable"
                                @click="showEditForm(scope.row)"><el-icon>
                                    <Edit />
                                </el-icon>修改</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="paginationContainer">
                    <el-pagination v-model:current-page="tableGridObj.paginationConfig.pageNo"
                        v-model:page-size="tableGridObj.paginationConfig.pageSize" :page-sizes="[20, 60, 120]"
                        layout="total, sizes, prev, pager, next, jumper" :total="tableGridObj.paginationConfig.total"
                        @size-change="tableGridObj.handleSizeChange"
                        @current-change="tableGridObj.handleCurrentChange" />
                </div>
            </el-card>
        </div>

        <el-dialog v-model="isShowForm" :title="formTitle" @closed="formCloseCallBack" :close-on-click-modal="false">
            <div class="containerbody">
                <configAbleForm ref="configForm" v-model:form-data="formData" :form-item-configs="formFieldsConfig"
                    :form-type="formType" :table-grid-id="TABLEGRIG_UUID" />
            </div>
            <div class="bottomdbody" v-if="formType === 'add' || formType === 'edit'">
                <el-button @click="closePanel">取消</el-button>
                <el-button type="primary" @click="uploadFormData">{{ uploadButtonName }}</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script lang='ts' setup name='tableGrid'>
import { onMounted, reactive, ref, toRaw } from "vue";
import { Plus, Delete, Edit, View } from "@element-plus/icons-vue";
import configAbleForm from "./components/configAbleForm/index.vue";
import queryForm from "./components/queryForm/index.vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { initConfig } from "./hooks/initfieldConfig";
import { getTableGridObjById } from "./hooks/dealData";

const props = defineProps({
    tableGridConfig: {
        type: Array<formTableConfig>,
        required: true
    }
})

const tableRef = ref();
const allCheck = ref(false);

const TABLEGRIG_UUID = Math.random().toString(16).slice(2);
const configForm = ref();
const isDisableDelete = ref(true);
const searchFormData = ref<any>({});

const isShowForm = ref(false);
const formData = ref<any>({});
const formType = ref('add');
const formTitle = ref('新增表单');
const uploadButtonName = ref('添加');

const tableGridConfigObj = initConfig(TABLEGRIG_UUID, props.tableGridConfig[0]);
const formFieldsConfig = ref<Array<fieldConfig>>(tableGridConfigObj.fieldConfigs.filter(field => !field.isDefaultValue));
const queryFieldsConfig = ref<Array<fieldConfig>>(tableGridConfigObj.fieldConfigs.filter(field => field.isQueryCondition));
const tableFieldsConfig = ref<Array<fieldConfig>>(tableGridConfigObj.fieldConfigs.filter(field => field.isShowInTable));
const tableGridObj = reactive(getTableGridObjById(TABLEGRIG_UUID));
const selectedRows = ref<any[]>([]);

// 表格选择
const checkAllChange = function (value: boolean) {
    allCheck.value = value
    if (value) {
        setAllTableCheck(tableGridObj.tableData)
    } else {
        setAllTableCheck()
    }
}
const setAllTableCheck = function (rows?: any[]) {
    if (rows) {
        tableRef.value.clearSelection()
        rows.forEach((row) => {
            tableRef.value.toggleRowSelection(row, undefined)
        })
    } else {
        tableRef.value.clearSelection()
    }
}
const handleSelectChange = () => {
    allCheck.value = false
}

// 查询工具函数
function searchData() {
    tableGridObj.searchTableData(searchFormData.value);
}

// 数据记录操作函数
function showDetails(rowData: any) {
    formTitle.value = '查看';
    formType.value = 'view';
    isShowForm.value = !isShowForm.value;
    formData.value = JSON.parse(JSON.stringify(toRaw(rowData)));
}

function showEditForm(rowData: any) {
    formTitle.value = '修改';
    formType.value = 'edit';
    uploadButtonName.value = '修改';
    isShowForm.value = !isShowForm.value;
    formData.value = JSON.parse(JSON.stringify(toRaw(rowData)));
}

function showAddForm() {
    formTitle.value = '新增';
    formType.value = 'add';
    uploadButtonName.value = '添加';
    isShowForm.value = !isShowForm.value;
    formData.value = {};
}

// 表单面板关闭函数
function formCloseCallBack() {
    formData.value = {};
    configForm.value.formObj.clearValidate();
}

function closePanel() {
    isShowForm.value = !isShowForm.value;
}

// 表格选中及删除逻辑
function tableSelectChange(rowSelection: any[]) {
    if (rowSelection.length) {
        isDisableDelete.value = false;
    } else {
        isDisableDelete.value = true;
    }
    selectedRows.value = rowSelection;
}

function deleteRow() {
    ElMessageBox.confirm(
        `确定删除${selectedRows.value.length}行记录吗？`,
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        const deleteIDs = selectedRows.value.map(item => item.id).join(',');
        tableGridObj.deleteRows(deleteIDs).then((res: any) => {
            if (res.code === 200) {
                ElMessage({
                    message: '删除成功！',
                    type: 'success',
                });
            } else {
                ElMessage.error('删除失败，请联系管理员！');
            }
        });
    })
}

// 新增或编辑提交数据函数
function uploadFormData() {
    configForm.value.formObj.validate((isValidate: boolean) => {
        if (!isValidate) {
            return
        }
        /** 新增或修改的逻辑 */
        if (formType.value === 'add') {
            tableGridObj.addRow(formData.value).then((res: any) => {
                if (res.code === 200) {
                    ElMessage({
                        message: '添加成功！',
                        type: 'success',
                    });
                    isShowForm.value = !isShowForm.value;
                } else {
                    ElMessage.error('添加失败，请联系管理员！');
                }
            });
        } else if (formType.value === 'edit') {
            tableGridObj.editRow(formData.value).then((res: any) => {
                if (res.code === 200) {
                    ElMessage({
                        message: '修改成功！',
                        type: 'success',
                    });
                    isShowForm.value = !isShowForm.value;
                } else {
                    ElMessage.error('修改失败，请联系管理员！');
                }
            });
        }
    })
}

onMounted(async () => {
    tableGridObj.getTableData();
})
</script>

<style lang="scss" scoped>
.table-grid {
    padding: 10px
}

.headButton {
    width: 100%;
    margin-bottom: 15px;
    
    .queryContainer {
        width: 100%;
        display: flex;
        align-items: center;

        .queryContent {
            width: 100%;
            display: flex;
            align-items: center;
            padding: 15px 15px 30px 15px;
            border: 1px solid #ddd;
            border-radius: 6px;
        }
    }
}

.tableContainer {

    .page_card_header {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .page_card_header_title {
            font-size: 16px;
            font-weight: 700;
            color: #333;
        }

        .page_card_header_btn {
            display: flex;

        }
    }

    .page_card_header_toolbar {
        margin-top: 14px;
        height: 40px;
        background: #f3f9ff;
        border: 1px solid #a0cffd;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 16px 0 20px;

        .page_card_header_toolbar_right {
            span {
                font-size: 14px;
                font-weight: 400;
                margin-left: 16px;
                cursor: pointer;
            }
        }
    }

    .paginationContainer {
        height: 50px;
        display: flex;
        justify-content: end;
        align-items: center;
    }

    :deep(.el-color-picker__trigger) {
        width: 120px;

        .el-color-picker__color-inner {
            padding-right: 5px;
            justify-content: right;
        }
    }
}

.containerbody {
    width: 100%;
}

.bottomdbody {
    width: 100%;
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: center;
}

:deep(.el-dialog__body) {
    max-height: 740px;
}

:deep(.el-dialog) {
    --el-dialog-margin-top: 10vh;
}
</style>
